package CookieDemo;

import Utils.CookieUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet(value = "/LastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Origin", "*");
        request.setCharacterEncoding("UTF-8");
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtil.getCookie(cookies, "lastVisited");
        if (cookie == null) {
            response.getWriter().write("欢迎第一次访问");
        }else {
            String time = cookie.getValue();
            time = URLDecoder.decode(time,"UTF-8");
            response.getWriter().write("上次访问时间:"+time);
        }
        String time = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        String encodedTime = URLEncoder.encode(time, "UTF-8");
        Cookie lastVisted = new Cookie("lastVisited", encodedTime);
        lastVisted.setPath(request.getContextPath());
        lastVisted.setMaxAge(7*24*60*60);
        response.addCookie(lastVisted);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
